"""
-------------------------------
- File_Name: logs.py
- Date: 2025/4/17
- Author: yangzhide
- Email: xxzjyzd@126.com
- Description: 日志管理
-------------------------------
"""
import json

from tortoise.queryset import Q
from fastapi import APIRouter, Query
from app.models.system.admin import APILog
from app.utils.ormUtil import OrmCRUD
from app.utils.responseUtil import ResponseUtil
from app.schemas import BaseResponse, BaseResponseExtra
from app.schemas.system.logs import SystemLog

router = APIRouter(prefix="/systemManage")
tags = ["系统日志管理"]
description = "系统日志管理相关信息"


# 对查询结果进行处理，提取所需的字段
def extract_specific_data(data):
    result = []
    for item in data:
        extracted_item = {
            "id": item.get("id", ""),
            "user_code": item.get("user_code", ""),
            "user_name": item.get("user_name", ""),
            "method": item.get("method", ""),
            "summary": item.get("summary", ""),
            "ip_address": item.get("ip_address", ""),
            "request_url": item.get("request_url", ""),
            "request_params": item.get("request_params") if item.get("request_params") else {},
            # "request_data": item.get("request_data", {}),# 这中写法不可行  数据库以json 格式存储, 如果是 None 则赋值为 {}
            "request_data": item.get("request_data") if item.get("request_data") else {},
            # 数据库以json 格式存储, 如果是 None 则赋值为 {}
            "response_data": item.get("response_data") if item.get("response_data") else {},
            "create_time": item.get("create_time", ""),
            "process_time": item.get("process_time", ""),
            "msg": item["response_data"].get("msg", ""),
        }
        result.append(extracted_item)
    return result


@router.get("/logs", summary="查询所有日志信息", response_model=BaseResponseExtra[SystemLog])
async def _(
        current: int = Query(1, description="当前页"),
        size: int = Query(10, description="每页条数"),
        user_name=Query("", alias="userName", description="操作人"),
        method=Query("", alias="method", description="请求方法"),
        ip_address=Query("", alias="ipAddress", description="ip地址"),
):
    # 返回的字段
    include_fields = ["id", "user_code", "user_name", "method", "summary", "ip_address", "request_url",
                      "request_params", "request_data","response_data", "create_time", "process_time"
                      ]
    # 原始查询集，不使用 await
    query = APILog.filter(
        ~(Q(summary__contains="查询所有日志信息") | Q(summary__contains="获取用户信息")),
        process_time__isnull=False,
        method__isnull=False,
        user_name__contains=user_name,
        method__contains=method,
        ip_address__contains=ip_address,
        # id='12557'
    )
    total = await query.count()
    queryset_data = await query.offset((current - 1) * size).limit(size).order_by("-id")
    data_dict = [await q.to_dict(include_fields) for q in queryset_data]
    data = extract_specific_data(data_dict)
    return ResponseUtil.success_response_extra(total, current, size, data, msg="查询日志信息成功")
